package com.lishe.lishe.lishe.module.me.fragments;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lishe.base.common.base.BaseFragment;
import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.asynchttp.LSWebHelper;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.auth.activity.AuthActivity;
import com.lishe.lishe.lishe.module.business.activity.BusinessActivity;
import com.lishe.lishe.lishe.module.coupon.activity.CouponActivity;
import com.lishe.lishe.lishe.module.excitation.fragment.ExcitationFragment;
import com.lishe.lishe.lishe.module.main.activity.MainActivity0;
import com.lishe.lishe.lishe.module.main.event.TabChangeEvent;
import com.lishe.lishe.lishe.module.me.activity.AboutUpdateActivity;
import com.lishe.lishe.lishe.module.me.activity.ActivitySetting;
import com.lishe.lishe.lishe.module.me.activity.AddressManageActivity;
import com.lishe.lishe.lishe.module.me.activity.AdviceActivity;
import com.lishe.lishe.lishe.module.me.activity.MyAccountActivity;
import com.lishe.lishe.lishe.module.me.bean.OrderType;
import com.lishe.lishe.lishe.module.me.bean.UserInfoObject;
import com.lishe.lishe.lishe.module.me.http.HttpUserCenter;
import com.lishe.lishe.lishe.module.myorder.activity.MyOrdersActivity;
import com.lishe.lishe.lishe.module.recharge.activity.RechargeIntegralActivity;
import com.lishe.lishe.lishe.utils.AppUtils;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.lishe.lishe.lishe.widget.CircleImageView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.List;

/**
 * Created by lwa on 2017/8/9.
 * 我的
 */

public class MineFragment extends BaseFragment implements View.OnClickListener {

    private TextView lab1, lab2, lab3, lab4, lab5;
    private ImageView recharge, Setting;
    private RelativeLayout order_waiting_pay, order_waiting_post, order_waiting_recieved, order_completion, order_cancel;
    private RelativeLayout relativeLayout;
    private boolean isCreate = true;

    private TextView username;
    private TextView totalPoints;
    private TextView commonPoints;
    private TextView limitPoints;
    private CircleImageView headIcon;
    private View rootView;// cache fragment view
    private TextView mTvCouponNum;
    private UserInfoObject mUserInfoObject;

    private volatile static MineFragment singleton = null;

    public static MineFragment getInstance()   {
        if (singleton == null)  {
            synchronized (MineFragment.class) {
                if (singleton == null)  {
                    singleton= new MineFragment();
                }
            }
        }
        return singleton;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.activity_mine, null);
            initView(rootView);
            setListener();
            IntentFilter filter = new IntentFilter();
            filter.addAction("REFRESH");
            rootView.setOnTouchListener(this);
        }
        return rootView;
    }

    @Override
    public void setMenuVisibility(boolean menuVisible) {
        super.setMenuVisibility(menuVisible);
        if (getView() != null) {
            this.getView().setVisibility(menuVisible ? View.VISIBLE : View.GONE);
        }
    }

    protected void initView(View v) {
        lab1 = v.findViewById(R.id.lab1);
        lab2 = v.findViewById(R.id.lab2);
        lab3 = v.findViewById(R.id.lab3);
        //lab4 = v.findViewById(R.id.lab4);
        lab5 = v.findViewById(R.id.lab5);

        order_waiting_pay = v.findViewById(R.id.order_wait_pay);
        order_waiting_recieved = v.findViewById(R.id.order_wait_recieved);
        order_waiting_post = v.findViewById(R.id.order_wait_post);
        //order_completion = v.findViewById(R.id.order_complete);
        order_cancel = v.findViewById(R.id.order_back);
        relativeLayout = v.findViewById(R.id.all_type_orders);
        Setting = v.findViewById(R.id.setting);
        recharge = v.findViewById(R.id.money);

        username = v.findViewById(R.id.user_name);
        totalPoints = v.findViewById(R.id.total_points);
        commonPoints = v.findViewById(R.id.common_points);
        limitPoints = v.findViewById(R.id.limit_points);
        headIcon = v.findViewById(R.id.head_icon);

        mTvCouponNum = v.findViewById(R.id.couponnum);
        v.findViewById(R.id.coupon_area).setOnClickListener(this);
        v.findViewById(R.id.assets_area).setOnClickListener(this);
        v.findViewById(R.id.address_area).setOnClickListener(this);
        v.findViewById(R.id.opinion_area).setOnClickListener(this);
        v.findViewById(R.id.about_area).setOnClickListener(this);
        //更新信息
        TextView version = v.findViewById(R.id.version);
        View updateIcon = v.findViewById(R.id.update_icon);
        int app_code = SharedPreferencesUtils.getAppCode();
        if (app_code != 0 && app_code > AppUtils.getVersionCode(context)) {
            updateIcon.setVisibility(View.VISIBLE);
            version.setVisibility(View.VISIBLE);
            String app_version = SharedPreferencesUtils.getAppVersion();
            if (!TextUtils.isEmpty(app_version))
                version.setText("V" + app_version);
        }
    }

    private void setListener() {
        relativeLayout.setOnClickListener(v -> {
            if (mUserInfoObject == null) {
                if (!LSWebHelper.getInstance().isUserLogined()) {
                    startActivity(new Intent(getActivity(), AuthActivity.class));
                } else {
                    HttpUserCenter.getUserInfoMain(null, response);
                }
                return;
            }
            MyOrdersActivity.jump(getActivity(), Globals.ORDER_TYPE_ALL);
        });
        order_cancel.setOnClickListener(this);
        order_waiting_post.setOnClickListener(this);
        order_waiting_pay.setOnClickListener(this);
        order_waiting_recieved.setOnClickListener(this);
        //order_completion.setOnClickListener(this);
        order_cancel.setOnClickListener(this);
        Setting.setOnClickListener(this);
        recharge.setOnClickListener(this);
    }


    LSWebHelper.WebCallBack response = new LSWebHelper.WebCallBack() {
        @Override
        public void onSuccess(JSONObject dataJson, String dataString, String message) {
            LoadingUtils.closeDialog();
            JSONObject userConfigs = dataJson;
            mTvCouponNum.setText(userConfigs.optString("couponNum") + "张可用");
            String userInfo = userConfigs.optString("userInfo");
            mUserInfoObject = JSON.parseObject(userInfo, UserInfoObject.class);
            setUserInfo(mUserInfoObject);
            String orderConfigs = userConfigs.optString("order_list_config");
            List<OrderType> list1 = JSON.parseArray(orderConfigs, OrderType.class);
            if (list1 != null && list1.size() > 0) {
                for (int i = 0; i < list1.size(); i++) {
                    OrderType order = list1.get(i);
                    setOrderData(order);
                }
            }
        }

        @Override
        public void onFailure(String message) {

            Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
            LoadingUtils.closeDialog();
        }
    };

    @Override
    public void onClick(View view) {
        if (mUserInfoObject == null) {
            if (!LSWebHelper.getInstance().isUserLogined()) {
                startActivity(new Intent(getActivity(), AuthActivity.class));
            } else {
                HttpUserCenter.getUserInfoMain(null, response);
            }
            return;
        }
        switch (view.getId()) {
            case R.id.coupon_area://我的优惠券
                startActivity(new Intent(getActivity(), CouponActivity.class));
                break;
            case R.id.assets_area://我的资产
                MyAccountActivity.jump(getActivity());
                break;
            case R.id.address_area://地址管理
                AddressManageActivity.jump(getActivity());
                break;
            case R.id.opinion_area://意见与反馈
                AdviceActivity.jump(getActivity());
                break;
            case R.id.about_area://关于礼舍
                AboutUpdateActivity.jump(getActivity());
                break;
            case R.id.all_type_orders:
                MyOrdersActivity.jump(getActivity(), Globals.ORDER_TYPE_ALL);
                break;
            case R.id.money:
                RechargeIntegralActivity.jump(getActivity());
                break;
            case R.id.order_wait_pay:
                MyOrdersActivity.jump(getActivity(), Globals.ORDER_TYPE_WAIT_PAY);
                break;
            case R.id.order_wait_post:
                MyOrdersActivity.jump(getActivity(), Globals.ORDER_TYPE_WAIT_SEND);
                break;
            case R.id.order_wait_recieved:
                MyOrdersActivity.jump(getActivity(), Globals.ORDER_TYPE_WAIT_RECEIVE);
                break;
            /*case R.id.order_complete:
                MyOrdersActivity.jump(getActivity(), Globals.ORDER_TYPE_OVER);
                break;*/
            case R.id.order_back:
                MyOrdersActivity.jump(getActivity(), Globals.ORDER_TYPE_COME_BACK);
                break;
            case R.id.setting:
                ActivitySetting.jump(getActivity(), mUserInfoObject.getMobile(), mUserInfoObject.getComName());
                break;
            case R.id.show_gift://晒福利
                BusinessActivity.jump(getActivity());
                break;
            default:
                break;

        }
    }

    private void setUserInfo(UserInfoObject user) {
        if (!TextUtils.isEmpty(user.getName())) {
            username.setText(String.format("%s，您好", user.getName()));
        } else {
            if (!TextUtils.isEmpty(user.getUsername())) {
                username.setText(String.format("%s，您好", user.getUsername()));
            } else {
                username.setText(String.format("%s，您好", user.getMobile()));
            }
        }

        totalPoints.setText(user.getBalance());
        commonPoints.setText(user.getCommonAmount());
        limitPoints.setText(user.getLimitAmount());
        if (!TextUtils.isEmpty(user.getUserAvatarPath()))
            ImageLoaderUtils.displayImage(this, user.getUserAvatarPath(), headIcon, R.mipmap.head);
    }

    private void setOrderData(OrderType order) {
        if (order.getTitle().equals("待付款")) {
            setLabs(lab1, order);

        } else if (order.getTitle().equals("待发货")) {
            setLabs(lab2, order);

        } else if (order.getTitle().equals("待收货")) {
            setLabs(lab3, order);

        } /*else if (order.getTitle().equals("已完成")) {
            setLabs(lab4, order);

        } */ else if (order.getTitle().equals("退货/款")) {
            setLabs(lab5, order);
        }
    }

    private void setLabs(TextView lab, OrderType order) {
        if (Integer.parseInt(order.getNumber()) > 0) {
            lab.setVisibility(View.VISIBLE);
            lab.setText(order.getNumber());
        } else {
            lab.setVisibility(View.GONE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!LSWebHelper.getInstance().isUserLogined()) {//未登录返回商城页
            EventBus.getDefault().post(new TabChangeEvent(0));
        } else {
            // 首次请求有加载中样式
            if (isCreate) {
                LoadingUtils.createLoadingDialog(getActivity(), "加载中", true);
                isCreate = false;
            }
            HttpUserCenter.getUserInfoMain(null, response);
        }
    }

}
